package org.jeecgframework.web.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.web.service.UploadCinemaService;
import org.jeecgframework.web.system.pojo.base.ZyFileLogEntity;
import org.jeecgframework.web.system.pojo.base.ZyUpCinemaCheckCmNameThread;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.FileBean;
import org.jeecgframework.web.util.StaticValue;
import org.jeecgframework.web.util.UploadFileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**   
 * @Title: UploadCinemaController
 * @Description: 上传影院信息
 * @author ZhangYunlong
 * @date 2016-04-01
 * @version V1.0   
 *
 */
@Scope("prototype")
@Controller
@RequestMapping("/uploadCinemaController")
public class UploadCinemaController extends BaseController {

	
	@Autowired
	private UploadCinemaService uploadCinemaService;
	@Autowired
	private SystemService systemService;
	
	/**
	 * 导入影院数据
	 * @return
	 */
	@RequestMapping(params = "uploadFile")
	public ModelAndView uploadFile(HttpServletRequest request) {
		return new ModelAndView("com/zybk/file_upload/uploadCinema");
	}
	
	@ResponseBody
	@RequestMapping(params = "importExcel")
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
		AjaxJson j = new AjaxJson();
		FileBean fileBean = UploadFileUtil.UploadFile(request);
		ZyFileLogEntity fileLog  = new ZyFileLogEntity();
		fileLog.setBusinessType(StaticValue.IMPORT_FILE_CINEMA_BASE_DATA); //文件业务
		fileLog.setOldFileName(fileBean.getFileRealName());//文件原名
		fileLog.setNewFileName(fileBean.getFileName());//文件新名
		fileLog.setFilePath(fileBean.getSavePath());
		fileLog.setFileType("xlsx");
		fileLog.setStatus("0");//文件新名
		systemService.save(fileLog);
		j.setObj(fileBean.getSavePath());
		return j;
	}
	
	/**
	 * @Description 解析EXCEL
	 * @param req
	 */
	@RequestMapping(params = "checkExcel")
	@ResponseBody
	public AjaxJson checkExcel(HttpServletRequest request, HttpServletResponse response){
		AjaxJson j = new AjaxJson();
		boolean flag = true;
		String msg = "导入成功";
		long begin = System.currentTimeMillis();
		List<String> cmNameList = uploadCinemaService.parseExcel(request,j);
		try {
			String repeatCmName = null;
			int maxUnit = 2000;
			int countRow = cmNameList.size();
			if(countRow > maxUnit){
	    		int threadC = countRow % maxUnit > 0 ? countRow / maxUnit + 1 : countRow / maxUnit;
	    		System.out.println("threadC:" + threadC);
	    		System.out.println("snList:" + cmNameList.size());
				ThreadPoolExecutor exec = (ThreadPoolExecutor) Executors.newFixedThreadPool(threadC);
	    		ArrayList<Future<String>> results = new ArrayList<Future<String>>();      
				for (int i = 0; i < threadC; i++) {
					int beginR = i * maxUnit;
					int endR = i == (threadC -1) ? beginR + (countRow % maxUnit) -1 : (beginR + maxUnit - 1);
		            results.add(exec.submit(new ZyUpCinemaCheckCmNameThread(cmNameList,beginR,endR)));
				}
				do{
					for (Future<String> fs : results) {
						if (fs.isDone()) {
							if(null != fs.get() && !fs.get().equals("")){
								msg = "影院名：" + fs.get().trim() + "，重复";
								flag = false;
								break;
							}
						}
					}
				}while(exec.getCompletedTaskCount() < results.size() && flag);
				exec.shutdown();
			}else{
				repeatCmName = uploadCinemaService.checkCmNameRepaet(cmNameList, 0, cmNameList.size() - 1);
				if(null != repeatCmName){
					msg = "影院名：" + repeatCmName.trim() + "，重复";
					flag = false;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		long end = System.currentTimeMillis();
		System.out.println("解析并比对 影院名称 完毕，用时："+(end - begin) / 1000 +"." + (end - begin) % 1000 +"秒");
		j.setMsg(msg);
		j.setSuccess(flag);
		return j;
	}
	
	/**
	 * @author xiul
	 * 2016-6-17 上午11:12:39
	 * Description 对比完影院名称之后 保存数据 
	 * @param filePath 上传的excel保存路径
	 */
	@ResponseBody
	@RequestMapping(params="readExcel")
	public void readExcel(@RequestParam(value="filePath")String filePath){
		uploadCinemaService.readExcel(filePath);
	}
}
